package com.ykq.config;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ykq.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;

import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;


@Configuration
public class RouteConfig {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("oauth-server-router", r -> r.path("/oauth/taken")
                .filters(f -> f.modifyResponseBody(String.class, String.class,
                        (exchanges, s) -> {
                            JSONObject jsonObject = JSONUtil.parseObj(s);
                            String accessToken = jsonObject.getStr("access_token");
                            if (StringUtils.hasText(accessToken)) {
                                Long expiresIn = jsonObject.getLong("expires_in");
                                redisTemplate.opsForValue().set(GatewayConstant.TOKEN_JWT_PREFIX + accessToken, "", Duration.ofSeconds(expiresIn));
                            }
                            return Mono.just(s);
                        })).uri("lb://auth-server"));
        return routes.build();

    }

}
